var onPlayItemUpdate = function (itemPos, updateInfo, itemName) {
  var playerName = updateInfo.getNewValue("player_name");
  var playerId = updateInfo.getNewValue("player_id");
  var playType = updateInfo.getNewValue("play_type");
  var metadata = jQuery.parseJSON(updateInfo.getNewValue("metadata"));
  var message = metadata["message"];

  if((playType == "drop" || playType == "dry" || playType == "undry") && playerId != window.currentPlayer) {
	processDrop(metadata, playerId, playerName, playType, metadata["message"]);
  }
  else if(playType == "get_cards") {
	$(".played-card-" + playerId).fadeIn("slow");
  }
  else if(playType == "ready") {
	 processUpdate(playerId, message, dateFormat(new Date(), "h:MM TT"), playerName,
	     "game", avatarMap[playerId]);
  }
  else if(playType == "deal") {
	$(".played_card_for_board").fadeOut();
	$(".dry_banner").fadeOut();
    $(".played_card").animate({opacity: 0.1}, 500).attr("src", '/site_media/images/cards/back.png');

    processUpdate(playerId, message, dateFormat(new Date(), "h:MM TT"), playerName,
      "game", avatarMap[playerId]);

    var mex = "GAME_PLAY|" + window.currentGame + "|" + window.currentPlayer + "|" + playerMap[currentPlayer] + "|get_cards|";
    if (engineRef != null) {
      engineRef.sendMessage(mex, null, 5000);
    }

    $.post("/getBots/", { "game_id":window.currentGame })
    .success(function(data) {
      for (botCounter=0; botCounter < data["bots"].length; botCounter++) {
    	  $(".played-card-" + data["bots"][botCounter]).fadeIn("slow");
      }
    });
    updateGameState();
  }
  else if(playType == "get_cards") {
    $(".played-card-" + playerId).fadeIn();
  }
};

function processDrop(metadata, playerId, playerName, playType, message) {
  var cards = metadata["cards"].split(",");
  var cardIndeces = metadata["card_indeces"].split(",");
  var cardNumbers = metadata["card_numbers"].split(",");

  for(i = 0; i < cards.length; i++){
    var card = cards[i];
	processDropForBoard(card, playerId, cardNumbers[i], playType, cardIndeces[i]);
  }
  processUpdate(playerId, message, dateFormat(new Date(), "h:MM TT"),
    playerName, "game", avatarMap[playerId]);
  updateGameState();
}

function updateGameState() {
	$.post("/getGameState/", { "game_id": window.currentGame})
	.success(function(data) {
      console.log(data);
	  updateGameStates(data);
	});
}

function updateGameStates(gameState) {
  var hand = gameState["hand"];
  var dries = gameState["dries"];
  console.log("my hand: " + hand);
  processHand(hand);
  for(var i = 0; i < hand.length; i++){
	var card = hand[i];
	console.log("A card a drac:" + card);
    if (card != null) {
      $("#drop_card").html("<i class='icon-share-alt icon-white'></i>&nbsp&nbspPlay</button>");
      $("#drop_card").removeClass("dry_mode");
      break;
    }
    if (dries.length > 0) {
      $("#drop_card").html("<i class='icon-share-alt icon-white'></i>&nbsp&nbspNext Dry</button>");
      $("#drop_card").addClass("dry_mode");
    }
  }

  var turnPlayer = gameState["turn_player"];
  var leadPlayer = gameState["lead_player"];
  var cardToBeat = gameState["card_to_beat"];
  var lostPlayers = gameState["lost_players"];
  var inProgress = gameState["in_progress"];
  var playerReady = gameState["player_ready"];
  var gameReady = gameState["game_ready"];
  isTurn = (turnPlayer == window.currentPlayer);
  isLead = (leadPlayer == window.currentPlayer);

  if (!playerReady && !gameReady && inProgress && hand.length > 0) {
	$("#ready_button").fadeIn();;
    $("#dry_button").removeAttr("disabled");
    $("#show_dry_button").removeAttr("disabled");
    $("#under_ten_button").removeAttr("disabled");
  } else {
 	$("#ready_button").fadeOut();
    $("#dry_button").attr("disabled", "disabled");
    $("#show_dry_button").attr("disabled", "disabled");
    $("#under_ten_button").attr("disabled", "disabled");
  }

  console.log("isTurn: " + isTurn);
  console.log("ready: " + playerReady);
  console.log("inProgress: " + inProgress);
  if (isTurn && playerReady && inProgress) {
	alertMode = true;
	alertPlayer(document.title, "It's your turn to play");
    $("#drop_card").removeAttr("disabled");
  } else {
    $("#drop_card").attr("disabled", "disabled");
  }
  var winner = gameState["winner"];
  var inProgress = gameState["in_progress"];
  var scores = gameState["scores"];
  var dealer = gameState["dealer"];

  if (inProgress || winner) {
	$(".card-back").show();
  }
  updateWinnerGameOverAndPoints(winner, inProgress, scores, dealer);

  $(".played_card").css("border", '1px solid lightgrey');
  $(".played_card").each(function(i, object){
	if($(object).attr('fileFormat') == cardToBeat){
	  $(object).css("border", '1px solid #468847');
	}
  });

  $("[name='playing_span']").css({ opacity: 0.0 });
  $("[name='lead_span']").css({ opacity: 0.0 });
  $("[name='dealer_span']").css({ opacity: 0.0 });
  $("#playing_of_" + turnPlayer).css({ opacity: 1.0 });
  $("#lead_of_" + leadPlayer).css({ opacity: 1.0 });
  $("#dealer_of_" + dealer).css({ opacity: 1.0 });
}

function updateWinnerGameOverAndPoints(winner, inProgress, scores, dealer){

  for (var player in scores) {
	    $("#won_of_" + player).text(scores[player]["total_won"]);
	    $("#score_of_" + player).text(scores[player]["total_points"]);
  }

  if (!inProgress) {
	  alertMode = false;
	  if (dealer == window.currentPlayer) {
		$("#deal_button").removeAttr("disabled");
		$("#deal_button").addClass("btn-info");
		$("#deal_button").removeClass("btn-success");
		$("#deal_button").html("<i class='icon-refresh icon-white'></i>&nbsp&nbspDeal Cards");
		$("#deal_button").fadeIn();
	  }
  }
}

function processDropForBoard(card, playerId, cardNumber, playType, cardIndex){
  console.log("Player: " + playerId + ", Play Type: " + playType);

  if (playType == "undry") {
    $("#played-card-" + playerId + "-" + cardNumber).attr("src", "/site_media/images/cards/back.png");
    $("#played-card-" + playerId + "-" + cardNumber).css("opacity", 0.1);
    $("#dried-card-" + playerId + "-" + cardNumber).fadeOut();
    $("#dried-card-" + playerId + "-" + cardNumber).parent().removeClass("dry_play");
    if (playerId == currentPlayer) {
	  console.log("before dropped " + dryCardNumbers);
	  if (window.dryCardNumbers.indexOf(cardNumber) != -1) {
		window.dryCardNumbers.splice(window.dryCardNumbers.indexOf(cardNumber), 1);
	  }
	  console.log("after dropped " + dryCardNumbers);
	}
    return;
  }

  showCard(card, playerId, cardNumber, playType, cardIndex);

  if (playType == "drop") {
	  if (playerId == currentPlayer) {
		console.log("before dropped " + dryCardNumbers);
		if (window.dryCardNumbers.indexOf(cardNumber) != -1) {
			window.dryCardNumbers.splice(window.dryCardNumbers.indexOf(cardNumber), 1);
		}
		console.log("after dropped " + dryCardNumbers);
	  }
	  $("#current_card_image").attr("src", "/site_media/images/cards/" + card + ".png");
	  $("#played-card-" + playerId + "-" + cardNumber).parent().fadeIn();
	  var currentCardForBoard = $("#current_card_image").clone();
	  currentCardForBoard.removeAttr("id");
	  currentCardForBoard.attr("fileFormat", card);
	  currentCardForBoard.css("height", "9.5em");
	  currentCardForBoard.css("width", "auto");
	  currentCardForBoard.addClass("played_card_for_board");
	  if (cardPos != 0){
		  currentCardForBoard.css("margin-left", "-6em");
	  }
	  else {
		  cardPos = 1;
	  }
	  var degrees = getRandom();
	  currentCardForBoard.css("-ms-transform", "rotate(" + degrees + "deg)");
	  currentCardForBoard.css("-moz-transform", "rotate(" + degrees + "deg)");
	  currentCardForBoard.css("-webkit-transform", "rotate(" + degrees + "deg)");
	  currentCardForBoard.css("-khtml-transform", "rotate(" + degrees + "deg)");
	  currentCardForBoard.draggable({ containment: "#game_area", revert: true});
	  $("#played-card-" + playerId + "-" + cardNumber).parent().css("opacity", 1.0);

	  $("#board").append(currentCardForBoard);
	  currentCardForBoard.show();
	  currentCardForBoard.animate({ opacity: 1.0 }, 500);
  }
}

function hideCard(playerId, cardNumber) {
  $("#played-card-" + playerId + "-" + cardNumber).attr("src", "/site_media/images/cards/back.png");
  $("#played-card-" + playerId + "-" + cardNumber).css("opacity", 0.1);
  $("#played-card-" + playerId + "-" + cardNumber).addClass("faded");
}

function showCard(card, playerId, cardNumber, playType, cardIndex) {
  $("#played-card-" + playerId + "-" + cardNumber).show();
  $("#played-card-" + playerId + "-" + cardNumber).attr("src", "/site_media/images/cards/" + card + ".png");
  $("#played-card-" + playerId + "-" + cardNumber).attr("fileFormat", card);
  $("#played-card-" + playerId + "-" + cardNumber).attr("rel", cardIndex);
  $("#played-card-" + playerId + "-" + cardNumber).animate({ opacity: 1.0 }, 500);
  $("#played-card-" + playerId + "-" + cardNumber).attr("play_type", playType);

  if (playType == "dry") {
	$("#dried-card-" + playerId + "-" + cardNumber).fadeIn();
	$("#played-card-" + playerId + "-" + cardNumber).parent().fadeIn();
	$("#played-card-" + playerId + "-" + cardNumber).parent().addClass("dry_play");
	if (playerId == currentPlayer) {
	  $("#played-card-" + playerId + "-" + cardNumber).parent().css("opacity", 0.6);
	}
	window.dryCardNumbers.push(cardNumber);
	window.dryCardNumbers.sort();
	console.log("dried " + window.dryCardNumbers);
  }
}

function processHand(cards) {
	var j = 0;
    $(".card").each(function(i, object){
      while(!cards[j] && j < cards.length){
        j++;
      }
      if(cards[j]){
        $(object).attr('src', '/site_media/images/cards/' + cards[j] + '.png')
        $(object).attr('rel', cards[j]);
        $(object).attr('name', j);
        $("#card" + (i + 1)).fadeIn(500);
        j++;
      }
      else {
        $("#card" + (i + 1)).fadeOut(500);
      }
    });
}

function getRandom() {
	return Math.floor((Math.random() * 2 - 1) * 10);
}

function alertPlayer(oldTitle, newTitle) {
  if(!alertMode) {
	  document.title = oldTitle;
	  return;
  }
  var currTitle = document.title;
  if (currTitle == oldTitle) {
	  document.title = newTitle;
  }
  else {
	  document.title = oldTitle;
  }

  window.timer = window.setTimeout(function(){
	  alertPlayer(oldTitle, newTitle);
  }, 1000);
}
